package com.itjin.controller;

import com.itjin.model.domain.entity.HotUpdateConfig;
import com.itjin.model.domain.vo.HotUpdateConfigVO;
import com.itjin.model.result.Result;
import com.itjin.service.ConfigService;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/admin/config")
@Tag(name = "配置管理")
@Slf4j
public class ConfigController {

  @Autowired
  private ConfigService configService;

  /**
   * 添加配置
   */
  @Operation(summary = "添加配置")
  @PostMapping("/add")
  public Result<Boolean> addConfig(@RequestBody HotUpdateConfig config) {
    try {
      boolean success = configService.addConfig(config);
      return Result.success(success);
    } catch (IllegalArgumentException e) {
      log.error("添加配置参数错误: {}", e.getMessage());
      return Result.failure(400, e.getMessage());
    } catch (Exception e) {
      log.error("添加配置失败", e);
      return Result.failure(500, "添加配置失败: " + e.getMessage());
    }
  }

  /**
   * 更新配置
   */
  @Operation(summary = "更新配置")
  @PutMapping("/update")
  public Result<Boolean> updateConfig(@RequestBody HotUpdateConfig config) {
    try {
      boolean success = configService.updateConfig(config);
      return Result.success(success);
    } catch (IllegalArgumentException e) {
      log.error("更新配置参数错误: {}", e.getMessage());
      return Result.failure(400, e.getMessage());
    } catch (Exception e) {
      log.error("更新配置失败", e);
      return Result.failure(500, "更新配置失败: " + e.getMessage());
    }
  }

  /**
   * 删除配置
   */
  @Operation(summary = "删除配置")
  @DeleteMapping("/delete/{id}")
  public Result<Boolean> deleteConfig(@PathVariable Integer id) {
    try {
      boolean success = configService.deleteConfig(id);
      return Result.success(success);
    } catch (IllegalArgumentException e) {
      log.error("删除配置参数错误: {}", e.getMessage());
      return Result.failure(400, e.getMessage());
    } catch (Exception e) {
      log.error("删除配置失败", e);
      return Result.failure(500, "删除配置失败: " + e.getMessage());
    }
  }

  /**
   * 获取所有配置
   */
  @Operation(summary = "获取所有配置")
  @GetMapping("/list")
  public Result<List<HotUpdateConfig>> getAllConfigs() {
    try {
      List<HotUpdateConfig> configs = configService.list();
      return Result.success(configs);
    } catch (Exception e) {
      log.error("获取配置列表失败", e);
      return Result.failure(500, "获取配置列表失败: " + e.getMessage());
    }
  }

  /**
   * 上传APK文件并生成下载链接
   */
  @Operation(summary = "上传APK文件")
  @PostMapping("/upload")
  public Result<String> uploadApk(@RequestParam("file") MultipartFile file,
      @RequestParam("version") String version,
      @RequestParam("platform") String platform,
      @RequestParam(value = "description", required = false) String description,
      @RequestParam(value = "forceUpdate", required = false, defaultValue = "0") Integer forceUpdate) {
    try {
      if (file.isEmpty()) {
        return Result.failure(400, "上传文件不能为空");
      }

      // 检查文件类型
      String originalFilename = file.getOriginalFilename();
      if (originalFilename == null
          || (!originalFilename.toLowerCase().endsWith(".apk") && !originalFilename.toLowerCase().endsWith(".ipa"))) {
        return Result.failure(400, "只支持上传APK或IPA文件");
      }

      // 调用服务上传文件并生成配置
      String downloadUrl = configService.uploadApkAndGenerateConfig(file, version, platform, description, forceUpdate);
      return Result.success(downloadUrl);
    } catch (IllegalArgumentException e) {
      log.error("上传APK参数错误: {}", e.getMessage());
      return Result.failure(400, e.getMessage());
    } catch (Exception e) {
      log.error("上传APK失败", e);
      return Result.failure(500, "上传APK失败: " + e.getMessage());
    }
  }

  /**
   * 获取单个配置
   */
  @Operation(summary = "获取单个配置")
  @GetMapping("/get/{id}")
  public Result<HotUpdateConfig> getConfig(@PathVariable Integer id) {
    try {
      HotUpdateConfig config = configService.getById(id);
      if (config == null) {
        return Result.failure(404, "配置不存在");
      }
      return Result.success(config);
    } catch (Exception e) {
      log.error("获取配置失败", e);
      return Result.failure(500, "获取配置失败: " + e.getMessage());
    }
  }
}